#include "UsrAI.h"
#include<set>
#include <iostream>
#include<unordered_map>
using namespace std;
tagGame tagUsrGame;
ins UsrIns;
tagInfo info;
const int SEARCH_RANGE=10;
char Mymap[128][128]={0};
int begin_x=0,begin_y=0;
int begin_x1=0,begin_y1=0;
int begin_x2=0,begin_y2=0;
int begin_x3=0,begin_y3=0;
int start_x=0,start_y=0;
int begin_hx=0,begin_hy=0;
int center_x=0,center_y=0;
double enemyLandDR=0,enemyLandUR=0;
int homeCorner=0;
const int MAX_MAP_DR=128;
bool home_flag=false;
static int stage = 0;               // 阶段控制变量,初始为0
//村民分类列表
vector<tagFarmer>idleFarmer;               // 存储闲置的农民
vector<tagFarmer>fishingFarmer;            // 存储捕鱼的农民
vector<tagFarmer>cuttingFarmer;            // 存储砍树的农民
vector<tagFarmer>buildingHouseFarmer;      // 存储建造房子的农民
vector<tagFarmer>huntFarmer;               // 存储打猎的农民
vector<tagFarmer>buildDockFarmer;          // 存储建船坞的农民
vector<tagFarmer>dugFarmer;                // 存储挖矿石的农民
vector<tagFarmer>buildingguFarmer;         // 存储建造谷仓的农民
vector<tagArmy>exploringShips;
vector<tagArmy>enemyShips;
//映射表
map<int,int>SN_to_Sort;
map<int,tagResource>SN_to_Resource;
map<int,tagBuilding>SN_to_Building;
map<int,int>shipTask;
set<pair<int,int>>exploredAreas;
// 保存农民的历史状态：<农民SN, <工作目标, 资源, 记录时间>>
unordered_map<int, tuple<int, int>> farmerHistory;

void UsrAI::processData()
{
    info=getInfo();
    farmerManage();                     //遍历并统计农民情况
    initMap();                          //初始化地图
    if (homeCorner == 0)
        DetermineHomeCorner();
    //初始化市镇中心坐标
    if(center_x==0 && center_y==0){
        for(tagBuilding &building:info.buildings){
            if(building.Type==BUILDING_CENTER){
                center_x=building.BlockDR;
                center_y=building.BlockUR;
            }
        }
    }
    //阶段1：基础发展
    //建房(两个)
    House_build(2);
    //生产村民
    produce_farmer(9);
    //捕鱼(2人）
    Fishingtask(2);
    //砍树(2人)
    Cuttingtask(1);
    //建造船坞
    Dock_build();
    //船坞生产渔船（3艘）
    produce_sailing(3);
    //渔船捕鱼
    boatfishing();
    //砍树（4人）
    Cuttingtask(4);
    //打猎（4人）
    Huntingtask(4);
    //捕鱼（2人）
    Fishingtask(2);
    //建房（2个）
    House_build2(4);
    House_build(6);
    //建造谷仓
    Granary_build(1);
    //升级时代
    if(info.Meat>=500){
        int requiredBuildingCount = 0;
        for (tagBuilding& building : info.buildings) {
            // 建筑类型常量对应：船坞=10，仓库=3，兵营=7，谷仓=1
            if (building.Type == BUILDING_DOCK || building.Type == BUILDING_STOCK ||
                    building.Type == BUILDING_ARMYCAMP || building.Type == BUILDING_GRANARY) {
                requiredBuildingCount++;
            }
        }
        if (requiredBuildingCount < 2) {
            return; // 建筑数量不足，退出等待
        }
        // 查找市镇中心（唯一可执行升级的建筑）
        int townCenterSN = -1;
        for (tagBuilding& building : info.buildings) {
            if (building.Type == BUILDING_CENTER) { // 市镇中心类型常量=2
                // 确保市镇中心无正在执行的任务（Project == 0 表示空闲）
                if (building.Project == 0) {
                    townCenterSN = building.SN;
                    break;
                }
            }
        }
        if (townCenterSN == -1) {
            return; // 未找到可用的市镇中心，退出
        }
        // 执行升级命令（建筑动作常量：BUILDING_CENTER_UPGRADE = 2）
        BuildingAction(townCenterSN, BUILDING_CENTER_UPGRADE);
        stage++; // 进入升级后阶段
    }
    if(info.civilizationStage==CIVILIZATION_TOOLAGE){
        produce_farmer(18);
    }
    Cuttingtask(6);
    //建造市场
    Market_build(1);
    //采矿
    duggingtask(2);
    //升级伐木技术
    Upgradewood();
    //建造农田
    farm_build(1);
    //升级食物量
    Upgradefood();
    //升级采矿技术
    Upgradestone();
    //阶段2:海军建设与探索
    //建造运输船
    produce_boat(2);
    //建造战船
    produce_ship(4);
    // 更新探索船列表
    exploringShips.clear();
    for (tagArmy& army : info.armies) {
        if (army.Sort == AT_SHIP) {
            exploringShips.push_back(army);
        }
    }
    // 执行探索
    ExploreOcean();
    HandleEnemyShips();
    // 检查是否发现敌方大陆
    if (enemyLandDR == 0) {
        for (auto& building : info.enemy_buildings) {
            enemyLandDR = building.BlockDR;
            enemyLandUR = building.BlockUR;
            DebugText(QString("发现敌方大陆于(%1,%2)").arg(enemyLandDR).arg(enemyLandUR));
            break;
        }
    }
    return ;
}
void UsrAI::DetermineHomeCorner() {
    // 假设市镇中心坐标可以确定角落
    for (auto& building : info.buildings) {
        if (building.Type == BUILDING_CENTER) {
            if (building.BlockDR < 64 && building.BlockUR < 64)
                homeCorner = 0; // 左上
            else if (building.BlockDR >= 64 && building.BlockUR < 64)
                homeCorner = 1; // 右上
            else if (building.BlockDR < 64 && building.BlockUR >= 64)
                homeCorner = 2; // 左下
            else
                homeCorner = 3; // 右下
            break;
        }
    }
}
pair<int, int> UsrAI::GetOppositeCorner() {
    switch(homeCorner) {
        case 0: return {127, 127}; // 左上→右下
        case 1: return {0, 127};   // 右上→左下
        case 2: return {127, 0};    // 左下→右上
        case 3: return {0, 0};      // 右下→左上
        default: return {64, 64};
    }
}
// 战船探索逻辑
void UsrAI::ExploreOcean() {
    if (exploringShips.empty()) return;
    auto oppositeCorner = GetOppositeCorner();
    // 为每艘船分配探索任务
    for (size_t i = 0; i < exploringShips.size(); ++i) {
        tagArmy ship = exploringShips[i];
        if (ship.NowState != HUMAN_STATE_IDLE) continue;

        // 方法2：螺旋式探索（更全面）
        int range = 5 + i*2; // 不同船探索不同距离
        for (int d = -range; d <= range; d++) {
            for (int u = -range; u <= range; u++) {
                int targetDr = ship.BlockDR + d;
                int targetUr = ship.BlockUR + u;
                // 检查边界
                if (targetDr < 0 || targetUr < 0 ||
                    targetDr >= 128 || targetUr >= 128) continue;
                // 检查是否海洋且未探索
                if ((*info.theMap)[targetDr][targetUr].type == MAPPATTERN_OCEAN &&
                    exploredAreas.find({targetDr, targetUr}) == exploredAreas.end()) {
                    double targetDR = targetDr * BLOCKSIDELENGTH;
                    double targetUR = targetUr * BLOCKSIDELENGTH;
                    HumanMove(exploringShips[i].SN, targetDR, targetUR);
                    exploredAreas.insert({targetDr, targetUr});
                    goto nextShip;
                }
            }
        }
        nextShip:;
    }
}
// 遇敌处理
void UsrAI::HandleEnemyShips() {
    for (tagArmy& enemy : info.enemy_armies) {
        if (enemy.Sort == AT_SHIP && enemy.Blood > 0) {
            // 攻击
            if (exploringShips.size() ) {
                for (tagArmy&ship : exploringShips) {
                    int shipSN = ship.SN;
                    if (ship.NowState == HUMAN_STATE_IDLE) {
                        HumanAction(shipSN, enemy.SN);
                    }
                }
            }
            break;
        }
    }
}
//从市镇中心开始查找2*2的空地
int UsrAI::find_block(int &x,int &y){
    if(info.theMap ==nullptr){
        cout<<"info.theMap is null!"<<endl;
        return 0;
    }
    for(int i = begin_x ; i <=begin_x+SEARCH_RANGE; i++) {
        for (int j = begin_y+1; j <=begin_y+SEARCH_RANGE; j++) {
            if (i + 1 < 128 && j + 1 < 128) {
                // 检查四个位置是否都是陆地
                if ((*info.theMap)[i][j].type == MAPPATTERN_GRASS &&
                    (*info.theMap)[i + 1][j].type == MAPPATTERN_GRASS &&
                    (*info.theMap)[i][j + 1].type == MAPPATTERN_GRASS &&
                    (*info.theMap)[i + 1][j + 1].type == MAPPATTERN_GRASS) {
                    cout << "找到陆地: " << i << ", " << j << endl;
                // 检查高度是否相等（平地）
                    int height = (*info.theMap)[i][j].height;
                    if ((*info.theMap)[i + 1][j].height == height &&
                     (*info.theMap)[i][j + 1].height == height &&
                     (*info.theMap)[i + 1][j + 1].height == height) {
                            // 找到符合条件的2*2空地，返回左下角坐标
                             x = i;
                             y = j;
                             cout << "找到空地: " << x << ", " << y << endl;
                             return 1; // 返回1表示成功找到
                    }
                 }
              }
           }
       }
    return 0; // 返回0表示未找到合适的空地
}
//从已有的房屋开始查找2*2的空地
int UsrAI::find_2h_block(int &x,int &y){
    if(info.theMap ==nullptr){
        cout<<"info.theMap is null!"<<endl;
        return 0;
    }
    for(int i = begin_hx+1 ; i <=begin_hx+SEARCH_RANGE; i++) {
        for (int j = begin_hy; j <=begin_hy+SEARCH_RANGE; j++) {
            if (i + 1 < 128 && j + 1 < 128) {
                // 检查四个位置是否都是陆地
                if ((*info.theMap)[i][j].type == MAPPATTERN_GRASS &&
                    (*info.theMap)[i + 1][j].type == MAPPATTERN_GRASS &&
                    (*info.theMap)[i][j + 1].type == MAPPATTERN_GRASS &&
                    (*info.theMap)[i + 1][j + 1].type == MAPPATTERN_GRASS) {
                    cout << "找到陆地: " << i << ", " << j << endl;
                // 检查高度是否相等（平地）
                    int height = (*info.theMap)[i][j].height;
                    if ((*info.theMap)[i + 1][j].height == height &&
                     (*info.theMap)[i][j + 1].height == height &&
                     (*info.theMap)[i + 1][j + 1].height == height) {
                            // 找到符合条件的2*2空地，返回左下角坐标
                             x = i;
                             y = j;
                             cout << "找到空地: " << x << ", " << y << endl;
                             return 1; // 返回1表示成功找到
                    }
                 }
              }
           }
       }
    return 0; // 返回0表示未找到合适的空地
}
//从市镇中心开始寻找3*3的空地
int UsrAI::find_3x3_block(int &x, int &y) {
    if (info.theMap == nullptr) {
        cout << "info.theMap is null!" << endl;
        return 0;
    }
    // 从市镇中心附近开始搜索，确保3*3范围不越界
    for (int i=begin_x1-1; i <=begin_x1+SEARCH_RANGE; i++) {
        for (int j = begin_y1; j <=begin_y1+SEARCH_RANGE; j++) {
            //检查（i，j）是否在地图内，且3*3区域不越界
            if(i<2 ||i>=126||j<2||j>=126){
                continue;
            }
            // 检查3*3范围内所有格子是否为草地且高度一致
            bool isAllGrass = true;
            int height = (*info.theMap)[i][j].height;
            for (int di = 0; di < 3; di++) {
                for (int dj = 0; dj < 3; dj++) {
                    if(Mymap[i+di][j+dj]=='A'||Mymap[i+di][j+dj]=='a'){
                            isAllGrass=false;
                            break;
                }
                    if ((*info.theMap)[i + di][j + dj].type != MAPPATTERN_GRASS ||
                        (*info.theMap)[i + di][j + dj].height != height) {
                        isAllGrass = false;
                        continue;
                    }
                }
                if (!isAllGrass) continue;
            }
            if (isAllGrass) {
                x = i;
                y = j;
                cout << "找到3*3空地: " << x << ", " << y << endl;
                return 1; // 成功找到
            }
        }
    }
    return 0; // 未找到
}
//找农田的位置
int UsrAI::find_non_block(int &x, int &y) {
    if (info.theMap == nullptr) {
        cout << "info.theMap is null!" << endl;
        return 0;
    }
    // 从市镇中心附近开始搜索，确保3*3范围不越界
    for (int i=begin_x2+1; i < 128; i++) {
        for (int j = begin_y2; j < 128; j++) {
            //检查（i，j）是否在地图内，且3*3区域不越界
            if(i<2 ||i>=126||j<2||j>=126){
                continue;
            }
            // 检查3*3范围内所有格子是否为草地且高度一致
            bool isAllGrass = true;
            int height = (*info.theMap)[i][j].height;
            for (int di = 0; di < 3; di++) {
                for (int dj = 0; dj < 3; dj++) {
                    if(Mymap[i+di][j+dj]=='A'||Mymap[i+di][j+dj]=='a'){
                            isAllGrass=false;
                            break;
                }
                    if ((*info.theMap)[i + di][j + dj].type != MAPPATTERN_GRASS ||
                        (*info.theMap)[i + di][j + dj].height != height) {
                        isAllGrass = false;
                        continue;
                    }
                }
                if (!isAllGrass) continue;
            }
            if (isAllGrass) {
                x = i;
                y = j;
                cout << "找到3*3空地: " << x << ", " << y << endl;
                return 1; // 成功找到
            }
        }
    }
    return 0; // 未找到
}
//找市场的位置
int UsrAI::find_mar_block(int &x, int &y) {
    if (info.theMap == nullptr) {
        cout << "info.theMap is null!" << endl;
        return 0;
    }
    // 从市镇中心附近开始搜索，确保3*3范围不越界
    for (int i=begin_x3-SEARCH_RANGE; i < 128; i++) {
        for (int j = begin_y3-SEARCH_RANGE; j < 128; j++) {
            //检查（i，j）是否在地图内，且3*3区域不越界
            if(i<2 ||i>=126||j<2||j>=126){
                continue;
            }
            // 检查3*3范围内所有格子是否为草地且高度一致
            bool isAllGrass = true;
            int height = (*info.theMap)[i][j].height;
            for (int di = 0; di < 3; di++) {
                for (int dj = 0; dj < 3; dj++) {
                    if(Mymap[i+di][j+dj]=='A'||Mymap[i+di][j+dj]=='a'){
                            isAllGrass=false;
                            break;
                }
                    if ((*info.theMap)[i + di][j + dj].type != MAPPATTERN_GRASS ||
                        (*info.theMap)[i + di][j + dj].height != height) {
                        isAllGrass = false;
                        continue;
                    }
                }
                if (!isAllGrass) continue;
            }
            if (isAllGrass) {
                x = i;
                y = j;
                cout << "找到3*3空地: " << x << ", " << y << endl;
                return 1; // 成功找到
            }
        }
    }
    return 0; // 未找到
}
//建房
void UsrAI::House_build(int HOME_MAX){
    //初始化搜索的起始坐标
        if(begin_x==0 && begin_y==0){
            begin_x=center_x;
            begin_y=center_y;
        }
    //统计当前已建成的房屋数量
        int home_count=0;
        for(tagBuilding &building:info.buildings){
            if(building.Type==BUILDING_HOME){
                home_count++;
            }
        }
    //如果已建数量未达标，继续找空地建造房屋
        if(home_count<HOME_MAX){
            int new_home_x,new_home_y;//新房屋的坐标
            if(idleFarmer.size()){
                if(find_block(new_home_x,new_home_y)){
                    HumanBuild(idleFarmer[idleFarmer.size()-1].SN,BUILDING_HOME,new_home_x,new_home_y);
                    begin_x=new_home_x;
                    begin_y=new_home_y;
                }
                DebugText("安排农民"+QString::number(idleFarmer[idleFarmer.size()-1].SN)+"建房子");
                buildingHouseFarmer.push_back(idleFarmer[idleFarmer.size()-1]);              // 加入建房农民数组
                idleFarmer.pop_back();
            }
        }
}
void UsrAI::House_build2(int HOME_MAX){
    //统计当前已建成的房屋数量
        int home_count=0;
        for(tagBuilding &building:info.buildings){
            if(building.Type==BUILDING_HOME){
                home_count++;
            }
        }
        if(begin_hx==0&&begin_hy==0){
            for(tagBuilding &b :info.buildings){
                if(b.Type==BUILDING_HOME){
                    begin_hx=b.BlockDR;
                    begin_hy=b.BlockUR;
                }
            }
        }
    //如果已建数量未达标，继续找空地建造房屋
        if(home_count<HOME_MAX){
            int home_x,home_y;//新房屋的坐标
            if(idleFarmer.size()){
                if(find_2h_block(home_x,home_y)){
                    HumanBuild(idleFarmer[idleFarmer.size()-1].SN,BUILDING_HOME,home_x,home_y);
                    begin_hx=home_x;
                    begin_hy=home_y;
                }
                DebugText("安排农民"+QString::number(idleFarmer[idleFarmer.size()-1].SN)+"建房子");
                buildingHouseFarmer.push_back(idleFarmer[idleFarmer.size()-1]);              // 加入建房农民数组
                idleFarmer.pop_back();
            }
        }
}
//建谷仓
void UsrAI::Granary_build(int guMAX){
    //初始化搜索的起始坐标
        if(begin_x1==0 && begin_y1==0){
            begin_x1=center_x;
            begin_y1=center_y;
        }
        int guCount=0;
        for(tagBuilding &building:info.buildings){
            if(building.Type==BUILDING_GRANARY){
                guCount++;
            }
        }
        int dx,dy;//新房屋的坐标
        if(guCount<guMAX && info.Wood>=BUILD_GRANARY_WOOD ){
            if(idleFarmer.size()){
                if(find_3x3_block(dx,dy)){
                    HumanBuild(idleFarmer[idleFarmer.size()-1].SN,BUILDING_GRANARY,dx,dy);
                    begin_x1=dx;
                    begin_y1=dy;
                }
                buildingguFarmer.push_back(idleFarmer[idleFarmer.size()-1]);              // 加入建房农民数组
                idleFarmer.pop_back();
            }
        }
}
//建市场
void UsrAI::Market_build(int makMAX){
    //初始化搜索的起始坐标
        if(begin_x3==0 && begin_y3==0){
            begin_x3=center_x;
            begin_y3=center_y;
        }
        int makCount=0;
        bool hasGR=false;
        for(tagBuilding &building:info.buildings){
            if(building.Type==BUILDING_MARKET){
                makCount++;
            }
        }
        for(tagBuilding &building:info.buildings){
            if(building.Type==BUILDING_GRANARY){
               hasGR=true;
            }
        }
        int dx=0,dy=0;
        if(makCount<makMAX && info.Wood>=BUILD_MARKET_WOOD && hasGR &&info.civilizationStage==CIVILIZATION_TOOLAGE ){
            if(idleFarmer.size()){
                if(find_mar_block(dx,dy)){
                    HumanBuild(idleFarmer[idleFarmer.size()-1].SN,BUILDING_MARKET,dx,dy);
                    begin_x3=dx;
                    begin_y3=dy;
                }
                buildingguFarmer.push_back(idleFarmer[idleFarmer.size()-1]);              // 加入建房农民数组
                idleFarmer.pop_back();
            }
        }
}
//建造农田
void UsrAI::farm_build(int maxCount){
    //初始化搜索的起始坐标
        if(begin_x2==0 && begin_y2==0){
            begin_x2=center_x;
            begin_y2=center_y;
        }
    int dx=0,dy=0;
    int farmCount=0;
    bool hasma=false;
    for(tagBuilding&b:info.buildings){
        if(b.Type==BUILDING_FARM){
            farmCount++;
        }
    }
    for(tagBuilding &building:info.buildings){
        if(building.Type==BUILDING_MARKET){
           hasma=true;
        }
    }
    if(idleFarmer.size()&& info.Wood>=BUILD_FARM_WOOD && farmCount< maxCount&& hasma){
        if(find_non_block(dx,dy)){
            HumanBuild(idleFarmer[idleFarmer.size()-1].SN,BUILDING_FARM,dx,dy);
            begin_x2=dx;
            begin_y2=dy;
        }
        buildingHouseFarmer.push_back(idleFarmer[idleFarmer.size()-1]);              // 加入建房农民数组
        idleFarmer.pop_back();
    }
}

//建造船坞
void UsrAI::Dock_build(){
    while(idleFarmer.size()&&buildDockFarmer.size()<2) {
     int x=-1,y=-1;
     //计算距离村民最近的海洋的块坐标
     double dis = 1e6;
     for(size_t i = 0; i <info.resources.size() ; i++) {
         const tagResource& res=info.resources[i];
         if(res.Type!=RESOURCE_FISH||res.Cnt<=0)
             continue;
         double tempDistance = calDistance(idleFarmer[idleFarmer.size()-1].DR, idleFarmer[idleFarmer.size()-1].UR, res.DR, res.UR);
         if(dis > tempDistance) {
             dis = tempDistance;
             start_x=res.BlockDR;
             start_y=res.BlockUR;
         }
     }
       for(int i = start_x + 1; i < 128; i++) {
           for (int j = start_y + 1; j < 128; j++) {
               if (i + 1 < 128 && j + 1 < 128) {
                   // 检查四个位置是否都是海洋
                   if ((*info.theMap)[i][j].type == MAPPATTERN_OCEAN &&
                       (*info.theMap)[i + 1][j].type == MAPPATTERN_OCEAN &&
                       (*info.theMap)[i][j + 1].type == MAPPATTERN_OCEAN &&
                       (*info.theMap)[i + 1][j + 1].type == MAPPATTERN_OCEAN) {
                       // 检查高度是否相等
                           int height = (*info.theMap)[i][j].height;
                           if ((*info.theMap)[i + 1][j].height == height &&
                            (*info.theMap)[i][j + 1].height == height &&
                            (*info.theMap)[i + 1][j + 1].height == height) {
                                   // 找到符合条件的2*2空地，返回左下角坐标
                                    x = i;
                                    y = j;
                                    break;
                           }
                   }
                }
           }
           if(x!=-1)
               break;
       }
       if(x!=-1&&y!=-1){
           HumanBuild(idleFarmer[idleFarmer.size()-1].SN,BUILDING_DOCK,x,y);
           DebugText("安排农民"+QString::number(idleFarmer[idleFarmer.size()-1].SN)+"建船坞");
           buildDockFarmer.push_back(idleFarmer[idleFarmer.size()-1]);              // 加入建船坞农民数组
           idleFarmer.pop_back();
       }
    }
}
// 遍历并统计农民情况
void UsrAI::farmerManage (){
    for(tagFarmer myFarmer:info.farmers) {
        if(myFarmer.FarmerSort == 0){
// 将闲置农民加入数组
          if(myFarmer.NowState == HUMAN_STATE_IDLE )    idleFarmer.push_back(myFarmer);
          if(myFarmer.NowState == HUMAN_STATE_WORKING){
            int Type = SN_to_Sort[myFarmer.WorkObjectSN];
            // 状态对应
            if(Type == RESOURCE_TREE) cuttingFarmer.push_back(myFarmer);
            if(Type == RESOURCE_FISH) fishingFarmer.push_back(myFarmer);
            if(Type == BUILDING_HOME) buildingHouseFarmer.push_back(myFarmer);
            if(Type == BUILDING_DOCK) buildDockFarmer.push_back(myFarmer);
            if(Type == RESOURCE_GAZELLE) huntFarmer.push_back(myFarmer);
            if(Type == RESOURCE_STONE) dugFarmer.push_back(myFarmer);

          }
        }
    }
}
//农民砍树
void UsrAI::Cuttingtask(int maxCount){
    for(tagFarmer&farmer:cuttingFarmer){
        if(farmer.WorkObjectSN==0)
            continue;
        bool tree=false;
        for(tagResource&res:info.resources){
            if(res.SN==farmer.WorkObjectSN&&res.Cnt>0){
                tree=true;
                break;
            }
        }
        if(!tree){
            farmer.WorkObjectSN=0;
        }
    }
    for(tagFarmer&farmer:cuttingFarmer){
        if(farmer.WorkObjectSN==0){
            int newTreeSN=findResource(farmer,RESOURCE_TREE);
            if(newTreeSN!=0){
                farmer.WorkObjectSN=newTreeSN;
                HumanAction(farmer.SN,newTreeSN);//继续砍新树
            }
        }
    }
    while(idleFarmer.size()&&cuttingFarmer.size()<maxCount) {
        HumanAction(idleFarmer[idleFarmer.size()-1].SN, findResource(idleFarmer[idleFarmer.size()-1], RESOURCE_TREE));
        DebugText("安排农民" + QString::number(idleFarmer[idleFarmer.size()-1].SN) + "砍树");
        cuttingFarmer.push_back(idleFarmer[idleFarmer.size()-1]);            // 加入砍树农民数组
        idleFarmer.pop_back();
    }
}
//农民捕鱼
void UsrAI::Fishingtask(int maxCount){
    while(idleFarmer.size()&& fishingFarmer.size()<maxCount) {
         int fishSN=findResource(idleFarmer[idleFarmer.size()-1], RESOURCE_FISH);
         HumanAction(idleFarmer[idleFarmer.size()-1].SN, fishSN);
         DebugText("安排农民"+QString::number(idleFarmer[idleFarmer.size()-1].SN)+"捕鱼");
         fishingFarmer.push_back(idleFarmer[idleFarmer.size()-1]);              // 加入捕鱼农民数组
         idleFarmer.pop_back();
    }
}
//捕猎
void UsrAI::Huntingtask(int maxCount){
    for(tagFarmer&farmer:huntFarmer){
        if(farmer.WorkObjectSN==0)
            continue;
        bool gazelle=false;
        for(tagResource&res:info.resources){
            if(res.SN==farmer.WorkObjectSN&&res.Cnt>0){
                gazelle=true;
                break;
            }
        }
        if(!gazelle){
            farmer.WorkObjectSN=0;
        }
    }
    for(tagFarmer&farmer:huntFarmer){
        if(farmer.WorkObjectSN==0){
            int newgaSN=findResource(farmer,RESOURCE_GAZELLE);
            if(newgaSN!=0){
                farmer.WorkObjectSN=newgaSN;
                HumanAction(farmer.SN,newgaSN);//继续捕猎
            }
        }
    }
    while(idleFarmer.size()&& huntFarmer.size()<maxCount) {
        HumanAction(idleFarmer[idleFarmer.size()-1].SN, findResource(idleFarmer[idleFarmer.size()-1], RESOURCE_GAZELLE));
        DebugText("安排农民" + QString::number(idleFarmer[idleFarmer.size()-1].SN) + "捕猎");
        huntFarmer.push_back(idleFarmer[idleFarmer.size()-1]);            // 加入捕猎农民数组
        idleFarmer.pop_back();
    }
}
//挖矿
void UsrAI::duggingtask(int maxCount){
    for(tagFarmer&farmer:dugFarmer){
        if(farmer.WorkObjectSN==0)
            continue;
        bool stone=false;
        for(tagResource&res:info.resources){
            if(res.SN==farmer.WorkObjectSN&&res.Cnt>0){
                stone=true;
                break;
            }
        }
        if(!stone){
            farmer.WorkObjectSN=0;
        }
    }
    for(tagFarmer&farmer:dugFarmer){
        if(farmer.WorkObjectSN==0){
            int newstoSN=findResource(farmer,RESOURCE_STONE);
            if(newstoSN!=0){
                farmer.WorkObjectSN=newstoSN;
                HumanAction(farmer.SN,newstoSN);//继续采集新石头
            }
        }
    }
    while(idleFarmer.size()&&dugFarmer.size()<maxCount) {
        HumanAction(idleFarmer[idleFarmer.size()-1].SN, findResource(idleFarmer[idleFarmer.size()-1], RESOURCE_STONE));
        DebugText("安排农民" + QString::number(idleFarmer[idleFarmer.size()-1].SN) + "采矿");
        dugFarmer.push_back(idleFarmer[idleFarmer.size()-1]);            // 加入采矿农民数组
        idleFarmer.pop_back();
    }
}
//渔船捕鱼
void UsrAI::boatfishing(){
    //渔船采集渔场资源
    bool hasFish=false;
    for(tagResource&res:info.resources){
        if(res.Type==RESOURCE_FISH&&res.Cnt>0){
            hasFish=true;
            break;
        }
    }
    if(hasFish){
        for(tagFarmer& farmer:info.farmers){
            if(farmer.FarmerSort==2&&farmer.NowState==HUMAN_STATE_IDLE){
                int fishSN=findResource(farmer, RESOURCE_FISH);
                if(fishSN!=0){
                    HumanAction(farmer.SN,fishSN);
                    DebugText("安排渔船"+QString::number(farmer.SN)+"捕鱼");
                }
            }
        }
    }
}

//生产农民
void UsrAI::produce_farmer(int humanCount){
    for(tagBuilding&building:info.buildings){
        //如果市镇中心空闲，且有足够食物，且农民数量小于人口上限，则生产农民
        if(building.Type==BUILDING_CENTER&&building.Project==0&&info.Meat>=BUILDING_CENTER_CREATEFARMER_FOOD
                &&info.farmers.size()<=humanCount){
            BuildingAction(building.SN,BUILDING_CENTER_CREATEFARMER);
            break;
        }
    }
}
//船坞生产渔船
void UsrAI::produce_sailing(int maxCount){
    int fishingboat=0;
    for(tagFarmer&f:info.farmers){
        if(f.FarmerSort==2){
            fishingboat++;
        }
    }
    for (tagBuilding& building : info.buildings) {
         //如果渔船数量超过2艘就停止生产
         if(fishingboat>=maxCount)
             break;
         if (building.Type == BUILDING_DOCK && building.Project == 0 && info.Wood >= BUILDING_DOCK_CREATE_SAILING_WOOD ) {
             BuildingAction(building.SN, BUILDING_DOCK_CREATE_SAILING);
             break;
             }
    }
}
//船坞生产运输船
void UsrAI::produce_boat(int boatCount){
    int sum=0;
    for(tagFarmer&f:info.farmers){
        if(f.FarmerSort==1){
            sum++;
        }
    }
    for (tagBuilding& building : info.buildings) {
         if(sum>=boatCount)
             break;
         if (building.Type == BUILDING_DOCK && building.Project == 0 && info.Wood >= BUILDING_DOCK_CREATE_WOOD_BOAT_WOOD ) {
             BuildingAction(building.SN, BUILDING_DOCK_CREATE_WOOD_BOAT);
             break;
             }
    }
}
//船坞生产战船
void UsrAI::produce_ship(int maxCount){
    int sum=0;
    for(tagArmy&ship :info.armies){
        if(ship.Sort==AT_SHIP){
            sum++;
        }
    }
    for (tagBuilding& building : info.buildings) {
         //如果渔船数量超过1艘就停止生产
         if(sum>=maxCount)
             break;
         if (building.Type == BUILDING_DOCK && building.Project == 0 && info.Wood >= BUILDING_DOCK_CREATE_SHIP_WOOD ) {
             BuildingAction(building.SN, BUILDING_DOCK_CREATE_SHIP);
             break;
             }
    }
}
//市场升级伐木科技
void UsrAI::Upgradewood(){
    int marketSN=-1;
    for(tagBuilding &building:info.buildings){
        if(building.Type ==BUILDING_MARKET){
            marketSN=building.SN;
            break;
        }
    }
    if(marketSN!=-1){
        if(info.Meat>=BUILDING_MARKET_WOOD_UPGRADE_FOOD &&info.Wood>=BUILDING_MARKET_WOOD_UPGRADE_WOOD){
            for(tagBuilding &b:info.buildings){
                if(b.SN=marketSN && b.Project==0){
                    BuildingAction(marketSN,BUILDING_MARKET_WOOD_UPGRADE);//发送升级伐木的命令
                    break;
                }
            }
        }
    }
}
//市场升级农场食量
void UsrAI::Upgradefood(){
    int marketSN=-1;
    for(tagBuilding &building:info.buildings){
        if(building.Type ==BUILDING_MARKET){
            marketSN=building.SN;
            break;
        }
    }
    if(marketSN!=-1){
        if(info.Meat>=BUILDING_MARKET_FARM_UPGRADE_FOOD &&info.Wood>=BUILDING_MARKET_FARM_UPGRADE_WOOD){
            for(tagBuilding &b:info.buildings){
                if(b.SN=marketSN && b.Project==0){
                    BuildingAction(marketSN,BUILDING_MARKET_FARM_UPGRADE);//发送升级伐木的命令
                    break;
                }
            }
        }
    }
}
//市场升级采矿科技
void UsrAI::Upgradestone(){
    int marketSN=-1;
    for(tagBuilding &building:info.buildings){
        if(building.Type ==BUILDING_MARKET){
            marketSN=building.SN;
            break;
        }
    }
    if(marketSN!=-1){
        if(info.Meat>=BUILDING_MARKET_STONE_UPGRADE_FOOD ){
            for(tagBuilding &b:info.buildings){
                if(b.SN=marketSN && b.Project==0){
                    BuildingAction(marketSN,BUILDING_MARKET_STONE_UPGRADE);//发送升级伐木的命令
                    break;
                }
            }
        }
    }
}
//寻找最近资源
int UsrAI::findResource(tagFarmer farmer,int type){
    int targetResSN = 0;
    double dis = 1e6;
        // 计算出距离该村民最近的资源的全局编号SN
        for(tagResource&res:info.resources) {
            if(res.Type!=type||res.Cnt<=0)
                continue;
            double tempDistance = calDistance(farmer.DR, farmer.UR, res.DR, res.UR);
            if(dis > tempDistance) {
                dis = tempDistance;
                targetResSN = res.SN;
            }
        }
    return targetResSN;
}

void UsrAI::initMap(){
    for(int i=0;i<128;i++){
        for(int j=0;j<128;j++){
            if ((*info.theMap)[i][j].type == MAPPATTERN_GRASS){
                Mymap[i][j]='0';
            }
            else if((*info.theMap)[i][j].type ==MAPPATTERN_OCEAN){
                Mymap[i][j]='-';
            }
        }
    }
    mark_Resources();
    mark_Buildings();
    mark_Units();
}
void UsrAI::mark_Resources(){
    for(tagResource&resources:info.resources){
        if(resources.Type){
            int i=int (resources.BlockDR);
            int j=int (resources.BlockUR);
            Mymap[i][j]='A';
        }

    }
}
void UsrAI::mark_Buildings(){
    for(tagBuilding &building:info.buildings){
        if(building.Type){
            int i=building.BlockDR;
            int j=building.BlockUR;
            Mymap[i][j]='a';
        }

    }
}
void UsrAI::mark_Units(){
    for(tagFarmer&farmer:info.farmers){
        if(farmer.Blood){
            int i=farmer.BlockDR;
            int j=farmer.BlockUR;
            Mymap[i][j]='*';
        }
    };
}
